import java.io.IOException;

import javax.naming.Context;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.w3c.dom.Text;

public class IPCount {

    // Mapper 类：提取 IP 地址并输出 (IP, 1) 键值对
    public static class IPMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
        private final static IntWritable one = new IntWritable(1);
        private Text ip = new Text();

        @Override
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            // 假设日志格式为：IP地址 其他信息
            // 这里简单假设 IP 地址在每行的开头，以空格分隔
            String line = value.toString();
            String[] parts = line.split("\\s+");
            
            if (parts.length > 0) {
                // 提取 IP 地址
                ip.set(parts[0]);
                context.write(ip, one);
            }
        }
    }

    // Reducer 类：对相同 IP 的访问次数进行累加
    public static class IPReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
        private IntWritable result = new IntWritable();

        @Override
        public void reduce(Text key, Iterable<IntWritable> values, Context context) 
                throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            result.set(sum);
            context.write(key, result);
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
        
        if (otherArgs.length != 2) {
            System.err.println("Usage: IPCount <input> <output>");
            System.exit(2);
        }

        Job job = Job.getInstance(conf, "IP Count");
        job.setJarByClass(IPCount.class);
        
        // 设置 Mapper 和 Reducer
        job.setMapperClass(IPMapper.class);
        job.setReducerClass(IPReducer.class);
        
        // 设置输出键值对类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        
        // 设置输入输出路径
        FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
        FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
        
        // 提交作业并等待完成
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
} 